
<template>
  <div>{{ refResult }}</div>
  
</template>
<script setup>
import CryptoES from "crypto-es";
import { ref } from 'vue';
import {formatDateTimeUs , base64_encode} from '../utils/util'
defineProps({
  msg: String,
})
const refResult = ref('')
const ws = ref();
const initChart = () => {
  const host = 'spark-api.xf-yun.com';
  const path = '/v1.1/chat';
  const APISecret = 'NjZmNWE2Nzg1YTcwYWI2Njc5YWY5ZjY5';
  const APIKey = '86a7c023f4d129e86efd12f97a8527b5';
  const dateString = new Date().toGMTString();
  let tmp = "host: " + host + "\n"
  tmp += "date: " + dateString + "\n"
  tmp += "GET " + path + " HTTP/1.1"
  const signature = CryptoES.HmacSHA256(tmp,APISecret).toString(CryptoES.enc.Base64)
  const authorization_origin = btoa(`api_key="${APIKey}", algorithm="hmac-sha256", headers="host date request-line", signature="${signature}"`)
  const signUrl = `wss://${host}${path}?authorization=${authorization_origin}&date=${encodeURIComponent(dateString).replace(/%20/g,"+")}&host=${host}`
  ws.value = new WebSocket(signUrl)
  ws.value.onopen = () => {
    console.log("连接成功");

    ws.value.send(JSON.stringify({
			"header": {
				"app_id": '1e13253e',//替换成自己的app_id
				// "uid": "fd3f47e4-d",//最大长度32	每个用户的id，用于区分不同用户
			},
			"parameter": {
				"chat": {
					"domain": "lite",
					"temperature": 0.5,
					"max_tokens": 1024, //模型回答的tokens的最大长度
				}
			},
			"payload": {
				"message": {
					"text": [{
						"role": "user",
						"content": "1加1等于几"
					}, ]
				}
			}
		}))
  };
  //后端设置心跳，会每间隔一定时间，触发一次，根据内容变化处理逻辑
  ws.value.onmessage = (e) => {
    const msg = JSON.parse(e.data);
    console.log(msg.payload.choices.text, "广播返回的消息");
  };
  ws.value.onerror = (e) => {
    //断连后每5秒重连一次
    console.log("连接错误",e);
  };
  ws.value.onclose = (e) => {
    //断连后每5秒重连一次
    console.log("连接关闭",e);
  };
}
// initChart();
</script>

<style scoped>
</style>
